package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 今日佳人
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        // 条件 userid , 排序 DESC,分页 1
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return mongoTemplate.findOne(query, RecommendUser.class);// 执行上述条件获取user
    }

    // 主页推荐列表
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {
        // 条件,分页,排序
        Query query = Query.query(Criteria.where("toUserId").is(userId))
                .with(PageRequest.of(pageNum, pageSize, Sort.by(Sort.Order.desc("score"))));
        List<RecommendUser> userList = mongoTemplate.find(query, RecommendUser.class);
        return new PageInfo<RecommendUser>(0, pageNum, pageSize, userList);
    }

    @Override
    public double queryScore(Long userId, Long toUserId) {
        Query query =  Query.query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null){
            return 0;
        }
        return recommendUser.getScore();
    }
}
